#include "meshelper.h"

#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QTimer>
#include <qmessagebox.h>
#include "tool.h"
#include <CustomWidget/tipsdialog.h>

MesHelper::MesHelper(QObject *parent) : QObject(parent)
{

}

bool MesHelper::commitReport(bool result, QString details)
{
    QNetworkAccessManager manager;
    QNetworkRequest request;
    request.setRawHeader("Content-Type", "application/json");
    QString url = getSetting("reportUrl").toString();
    qDebug()<<"reportUrl:"<<url;
    request.setUrl(QUrl(url));

    QString sn = execShell(ROOT_PATH + "/tools/getSn.sh");
    //组包
    QJsonObject data;
    data.insert("sn", sn);
    data.insert("mac", getHostMacAddress());
    data.insert("result", result ? "PASS" : "FAIL");
    data.insert("swVersion", getSetting("swVersion").toString());
    data.insert("swBranch", getSetting("swBranch").toString());
    data.insert("product", getSetting("product").toString());
    data.insert("orderNo", "");
    qDebug()<<"提交报告请求JSON:"<<data;
    data.insert("details", details);
    QJsonDocument doc;
    doc.setObject(data);
    //发送请求
    QNetworkReply *reply = manager.post(request, doc.toJson());
    //设置请求定时
    QTimer timer;
    timer.setSingleShot(true);
    connect(&timer, &QTimer::timeout, [=](){
        if(reply->isRunning()){
            reply->abort();
        }
    });
    timer.start(timeout);
    //请求异步转同步，并展示等待UI
    TipsDialog dlg;
    dlg.setContent(tip);
    connect(&manager, SIGNAL(finished(QNetworkReply*)), &dlg, SLOT(close()));
    dlg.exec();
    //请求结果解析
    QString error = "未知错误";
    if(reply && reply->error() == QNetworkReply::NoError)
    {
        QJsonParseError jsonError;
        QJsonDocument doc = QJsonDocument::fromJson(reply->readAll(), &jsonError);
        //解包数据正确性判断
        if (jsonError.error != QJsonParseError::NoError && !doc.isNull()) {
            error = "返回内容json格式错误："+reply->readAll().simplified();
        }else{
            QJsonObject json = doc.object();
            qDebug()<<"返回json:"<<QString(doc.toJson());
            if(json.value("code").toInt()==200){
                return true;
            }
            error = "上传失败：\n"+QString(doc.toJson());
        }

    }else
    {
        error = "上传失败，网络问题："+reply->errorString();

    }
    reply->close();
    qDebug()<<error;
    QMessageBox::critical(nullptr, "错误", error);
    return false;
}

bool MesHelper::canLogin(QString user, QString pswd)
{
    QNetworkAccessManager manager;
    QNetworkRequest request;
    request.setRawHeader("Content-Type", "application/json");
    QString url = getSetting("canLoginUrl").toString();
    qDebug()<<"reportUrl:"<<url;
    request.setUrl(QUrl(url));
    //组包
    QJsonObject data;
    data.insert("user", user);
    data.insert("pswd", pswd);
    QJsonDocument doc;
    doc.setObject(data);
    //发送请求
    QNetworkReply *reply = manager.post(request, doc.toJson());
    //设置请求定时
    QTimer timer;
    timer.setSingleShot(true);
    connect(&timer, &QTimer::timeout, [=](){
        if(reply->isRunning()){
            reply->abort();
        }
    });
    timer.start(timeout);
    //请求异步转同步，并展示等待UI
    TipsDialog dlg;
    dlg.setContent(tip);
    connect(&manager, SIGNAL(finished(QNetworkReply*)), &dlg, SLOT(close()));
    dlg.exec();
    //请求结果解析
    QString error = "未知错误";
    if(reply && reply->error() == QNetworkReply::NoError)
    {
        QJsonParseError jsonError;
        QJsonDocument doc = QJsonDocument::fromJson(reply->readAll(), &jsonError);
        //解包数据正确性判断
        if (jsonError.error != QJsonParseError::NoError && !doc.isNull()) {
            error = "返回内容json格式错误："+reply->readAll().simplified();
        }else{
            QJsonObject json = doc.object();
            qDebug()<<"返回json:"<<QString(doc.toJson());
            if(json.value("code").toInt()==200){
                return true;
            }
            error = "账号验证失败：\n"+QString(doc.toJson());
        }

    }else
    {
        error = "账号验证失败，网络问题：\n"+reply->errorString();

    }
    reply->close();
    qDebug()<<error;
    QMessageBox::critical(nullptr, "错误", error);
    return false;
}

bool MesHelper::updateMesInfo()
{
    QNetworkAccessManager manager;
    QNetworkRequest request;
    request.setRawHeader("Content-Type", "application/json");
    QString type = "3";
    QString sn = execShell(ROOT_PATH + "/tools/getSn.sh");
    QString stationName = getSetting("stationName").toString();
    QString lineName = "B11";
    QString url = getSetting("mesUrl").toString();
    url = url + "?type="+type+"&param="+sn+"&stationName="+stationName+"&lineName="+lineName+"&errorCode=PASS";
    logD("mes url: "+url);
    request.setUrl(QUrl(url));
    //组包
    QJsonObject data;
    data.insert("sn", sn);
    data.insert("stationName", stationName);

    QJsonDocument doc;
    doc.setObject(data);
    //发送请求
    QNetworkReply *reply = manager.post(request, doc.toJson());
    qDebug()<<"发送JSON:"<<data;
    //设置请求定时
    QTimer timer;
    timer.setSingleShot(true);
    connect(&timer, &QTimer::timeout, [=](){
        if(reply->isRunning()){
            reply->abort();
        }
    });
    timer.start(timeout);
    //请求异步转同步，并展示等待UI
    TipsDialog dlg;
    dlg.setContent(tip);
    connect(&manager, SIGNAL(finished(QNetworkReply*)), &dlg, SLOT(close()));
    dlg.exec();
    //请求结果解析
    QString error = "未知错误";
    if(reply && reply->error() == QNetworkReply::NoError)
    {
        QJsonParseError jsonError;
        QJsonDocument doc = QJsonDocument::fromJson(reply->readAll(), &jsonError);
        //解包数据正确性判断
        if (jsonError.error != QJsonParseError::NoError && !doc.isNull()) {
            error = "返回内容json格式错误："+reply->readAll().simplified();
        }else{
            QJsonObject json = doc.object();
            qDebug()<<"返回json:"<<json;
            if(json.value("code").toInt()==200){
//                QMessageBox::information(nullptr, "信息", json.value("msg").toString());
                return true;
            }
            error = "mes过站失败：\n"+QString(doc.toJson());
        }

    }else
    {
        error = "mes过站失败，网络问题：\n"+reply->errorString();

    }
    reply->close();
    logD(error);
    QMessageBox::critical(nullptr, "错误", error);
    return false;
}

bool MesHelper::checkMesFlow(QString sn)
{
    QNetworkAccessManager manager;
    QNetworkRequest request;
    request.setRawHeader("Content-Type", "application/json");
    QString url = getSetting("mesFlowUrl").toString();
    QString stationName = getSetting("stationName").toString();
    qDebug()<<"mesFlowUrl:"<<url;
    request.setUrl(QUrl(url));
    //组包
    QJsonObject data;
    data.insert("sn", sn);
    data.insert("stationName", stationName);
    QJsonDocument doc;
    doc.setObject(data);
    //发送请求
    QNetworkReply *reply = manager.post(request, doc.toJson());
    qDebug()<<"发送json:"<<data;
    //设置请求定时
    QTimer timer;
    timer.setSingleShot(true);
    connect(&timer, &QTimer::timeout, [=](){
        if(reply->isRunning()){
            reply->abort();
        }
    });
    timer.start(timeout);
    //请求异步转同步，并展示等待UI
    TipsDialog dlg;
    dlg.setContent(tip);
    connect(&manager, SIGNAL(finished(QNetworkReply*)), &dlg, SLOT(close()));
    dlg.exec();
    //请求结果解析
    QString error = "未知错误";
    if(reply && reply->error() == QNetworkReply::NoError)
    {
        QJsonParseError jsonError;
        QJsonDocument doc = QJsonDocument::fromJson(reply->readAll(), &jsonError);
        //解包数据正确性判断
        if (jsonError.error != QJsonParseError::NoError && !doc.isNull()) {
            error = "返回内容json格式错误："+reply->readAll().simplified();
        }else{
            QJsonObject json = doc.object();
            qDebug()<<"返回json:"<<json;
            if(json.value("code").toInt()==200){
//                QMessageBox::information(nullptr, "信息", json.value("msg").toString());
                return true;
            }
            error = "流程检查失败：\n"+QString(doc.toJson());
        }

    }else
    {
        error = "流程检查失败，网络问题：\n"+reply->errorString();

    }
    reply->close();
    qDebug()<<error;
    QMessageBox::critical(nullptr, "错误", error);
    return false;
}


